#include <p18F4520.h>
#include "ieee_robot.h"
#include "motor.h"

/*
 *Function Name:init_ccp1
 *
 *Parameters: none
 *
 *Description: This functions initializes the CCP1
 * module to run as standard pwm single output. It
 * follows the sets in 16.4.9 section of
 * PIC18F4520 datasheet
 *Returns: nothing
 *
 */
void init_ccp1(void) {
    //set RC2/P1A as input by setting
    //TRISC.RC2 = 1
    //and set RD5/P1B as input as 
    //said in 16.4.9 of datasheet
    PIR1 = PIR1 & (~0x02); //clear TMR2IF
    PIE1 = clear_bit(PIE1,1); //clear TMR2IE

    //set the PR2 setting required for
    //20 kHz pwm setting
    PR2 = (unsigned char)FREQ_SETTING;
    
    //configure CCP1 for single output PWM
    //P1A active high
    CCP1CON = 0x0C;
    
    //set TMR2 prescaler to 1:4 (divide by 4)
    T2CONbits.T2CKPS1 = 0;
    T2CONbits.T2CKPS0 = 1;
}

/*
 *Function Name:start_ccp1
 *Parameters: none
 *Prerequisites: call to init_ccp1() has taken place 
 *Description: this functions
 *
 *Returns:
 *
 */

void start_ccp1(void) {
    //clear TMR2IF flag
    PIR1 = clear_bit(PIR1,1);
    
    //set TMR2ON bit
    T2CON = set_bit(T2CON,2);
     
    //wait until TMR2IF flag is set
    while (test_bit(PIR1,1) == 0);
    PIR1 = clear_bit(PIR1,1);

    //this operation is specified
    //in 16.4.9
    ECCP1AS = clear_bit(ECCP1AS,7);

	//set the directions bits as specified
	//RC6,RC0,RC1,RC2 outputs, all others inputs
    //PORTCbits.RC0 = 0;
    //PORTCbits.RC1 = 1;
    //Set_Motor_Forward();
}
